//
//  BKExchangeGoodsViewController.m
//  bestkeep
//
//  Created by yons on 16/12/5.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKExchangeGoodsViewController.h"
#import "BKMainCommon.h"
#import "BKExchangeGoodsModel.h"
#import "BKExchangeGoodsCell.h"
#import "BKEXGoodsDetailCell.h"
#import "BK_ExChangeGoods_Bottom_View.h"
#import "BK_ExChangeGoods_Header_View.h"
#import "BKIntegralBookViewController.h"
#import "Mediator+BKOrder.h"
#import "Ex_Goods_Footer.h"

#import "BK_OD_Color.h"
#import "BK_OD_Tool.h"


@interface UIScrollView(BKExchangeFooterView)

@property(nonatomic,strong) UIView *BKExchange_footerView;

@end

@implementation UIScrollView(BKExchangeFooterView)

static char const BKExchange_footerViewKey = '\0';

-(void)setBKExchange_footerView:(UIView *)BKExchange_footerView {
    objc_setAssociatedObject(self, &BKExchange_footerViewKey, BKExchange_footerView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if(BKExchange_footerView) {
        
        CGRect frame = BKExchange_footerView.frame;
        frame.origin.y = self.contentSize.height;
        
        CGFloat contentHeight = self.contentSize.height;
        if(contentHeight + CGRectGetHeight(frame) < CGRectGetHeight([[UIScreen mainScreen] bounds]) - 64 - 49) {
            CGFloat y = CGRectGetHeight([[UIScreen mainScreen] bounds]) - 64 - 49 - contentHeight - CGRectGetHeight(BKExchange_footerView.frame);
            frame.origin.y += y;
        }
        
        
        BKExchange_footerView.frame = frame;
        
        self.contentInset = UIEdgeInsetsMake(0, 0, CGRectGetHeight(BKExchange_footerView.frame), 0);
        
        [self addSubview:BKExchange_footerView];
        
    } else {
        self.contentInset = UIEdgeInsetsZero;
    }
}

-(UIView *)BKExchange_footerView {
    return objc_getAssociatedObject(self, &BKExchange_footerViewKey);
}

@end



@interface BKExchangeGoodsViewController ()<UITableViewDelegate,UITableViewDataSource,BKBottomViewDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)BKExchangeGoodsModel *model;
@property(nonatomic,strong)BK_ExChangeGoods_Bottom_View *bottomView_ExChangeGoods;
@property(nonatomic,strong)BK_ExChangeGoods_Header_View *headerView_ExChangeGoods;
@property(nonatomic,strong)ExceptionView *exceptionView;

@property(nonatomic,strong)NSMutableArray * marr_Section;


@end

@implementation BKExchangeGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setProperty];
    [self check_NetWork];
}

#pragma mark==================setProperty======================
-(void)setProperty{
    
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    self.title = @"兑换商品";
    
}


-(void)viewWillAppear:(BOOL)animated{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
}

#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self BK_getData_ExchangeGoods];
            
        }
            break;
            
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
            
        }
            break;
    }
    
}
#pragma mark -----数据请求------
-(void)BK_getData_ExchangeGoods{
    [LoadingView loadingShoppingCartInView:self.view];
    [BKIntegralCommon integralGoods_infoExchangeId:self.exchangeId callback:^(BOOL isSucess, id obj, NSError *error) {
        if (isSucess) {
            self.model =[BKExchangeGoodsModel mj_objectWithKeyValues:obj];
            [self Create_marr_Section];
            [self updateView];
        }
        [LoadingView dismiss];
    }];
}
#pragma mark ------数据请求成功后加载页面-----
-(void)updateView{
    
    /*
     * 底部按钮
     */
    _bottomView_ExChangeGoods = [[BK_ExChangeGoods_Bottom_View alloc]init];
    _bottomView_ExChangeGoods.deleaget  = self;
    [self.view addSubview:_bottomView_ExChangeGoods];
    [_bottomView_ExChangeGoods mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.height.mas_equalTo(49);
    }];
    [self.bottomView_ExChangeGoods updateBottomView:self.model];
    
    
    _headerView_ExChangeGoods = [[BK_ExChangeGoods_Header_View alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth*432.0f/750.0f)];
    _headerView_ExChangeGoods.bannerArray = self.model.goodsImgs;
    [_headerView_ExChangeGoods setImage];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, ScreenWidth*432.0f/750.0f+5.0f)];
    view.backgroundColor = RGB(241, 241, 241);
    [view addSubview:_headerView_ExChangeGoods];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableView.tableHeaderView = view;
    [_tableView registerClass:[BKExchangeGoodsCell class] forCellReuseIdentifier:NSStringFromClass([BKExchangeGoodsCell class])];
    [_tableView registerClass:[BKEXGoodsDetailCell class] forCellReuseIdentifier:NSStringFromClass([BKEXGoodsDetailCell class])];
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.top.mas_equalTo(self.view.mas_top);
        make.bottom.mas_equalTo(self.bottomView_ExChangeGoods.mas_top);
    }];
    
    [_tableView reloadData];
    

    _tableView.BKExchange_footerView = [Ex_Goods_Footer get_Ex_Goods_Footer];

    
}

#pragma mark ----------tableView Delegate------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    if ([cm.className isEqualToString:NSStringFromClass([BKExchangeGoodsCell class])]) {
        return [BKExchangeGoodsCell getCellHeightFromInfo:self.model heightForRowAtIndexPath:indexPath];
    }else if([cm.className isEqualToString:NSStringFromClass([BKEXGoodsDetailCell class])]){
        return [BKEXGoodsDetailCell getCellHeightFromInfo:self.model heightForRowAtIndexPath:indexPath];
    }
    return 0.00001;
    
}




-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    
    cell.selectionStyle = cm.selectionStyle;
    
    if ([cm.className isEqualToString:NSStringFromClass([BKExchangeGoodsCell class])]) {
        BKExchangeGoodsCell* ex_cell=(BKExchangeGoodsCell*)cell;
        [ex_cell getInfoGoods:self.model cellForRowAtIndexPath:indexPath];
    }else if([cm.className isEqualToString:NSStringFromClass([BKEXGoodsDetailCell class])]){
        BKEXGoodsDetailCell* ex_cell=(BKEXGoodsDetailCell*)cell;
        [ex_cell getInfoGoods:self.model cellForRowAtIndexPath:indexPath];
    }
    
    return cell;
    
        
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
     if ([cm.className isEqualToString:NSStringFromClass([BKExchangeGoodsCell class])]) {
         Mediator *mediator = [Mediator sharedInstance];
         UIViewController *detailVC = [mediator BKGD_goodsDetailViewController:self.model.goodsId saleTypes:@""];
         detailVC.view.backgroundColor = [UIColor whiteColor];
         
         [self.navigationController pushViewController:detailVC animated:YES];
     }

}
#pragma mark ---------bottomViewDelegate------------------
//赚取积分
-(void)makeScoresButtonAction:(UIButton *)sender{
    BKIntegralBookViewController *integralBookVC = [[BKIntegralBookViewController alloc]init];
    integralBookVC.urlString = @"http://cdn.bestkeep.cn/ui/mobile/html/Integral.html";
    integralBookVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:integralBookVC animated:YES];
}
- (void)scoresUnenoughButtonAction:(UIButton *)sender {//积分不够用
    
}
//兑换积分
-(void)exchangeScoresButtonAction:(UIButton *)sender{
    UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"确认要兑换吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alart show];
    
}
#pragma mark ---------UIAlertViewDelegate----------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0:
            
            break;
            
        case 1:
//            [self exchangeGoods];
            break;
            
        default:
            break;
    }
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            
            break;
            
        case 1:
            [self exchangeGoods];
            break;
            
        default:
            break;
    }
}

-(void)exchangeGoods{
    

    [BKIntegralCommon integralGoods_exchangeConfirm:self.model.exchangeId callback:^(BOOL isSucess, id obj, NSError *error) {
        if (isSucess) {
            NSArray *ordersArr = obj[@"data"][@"orders"];
            NSDictionary *itemDic = ordersArr[0];
            NSArray *array_order_items = [itemDic objectForKey:@"order_items"];
            NSDictionary *dic = array_order_items[0];
            NSMutableDictionary *param_dic = [NSMutableDictionary dictionary];
            NSLog(@"%@",self.model.exchangeId);
            [param_dic setValue:self.model.exchangeId forKey:@"integralGoodsId"];
            [param_dic setValue:dic[@"goods_reserve_id"] forKey:@"goods_reserve_id"];
            [param_dic setValue:dic[@"goods_id"] forKey:@"goods_id"];
            [param_dic setValue:dic[@"goods_amount"] forKey:@"amount"];
            [param_dic setValue:dic[@"goods_send_date"] forKey:@"sendDate"];
            [param_dic setValue:dic[@"userPrice"] forKey:@"userPrice"];
            [param_dic setValue:@"" forKey:@"goods_pro_rel1"];
            [param_dic setValue:@"" forKey:@"goods_pro_rel2"];
            [param_dic setValue:@"" forKey:@"goods_pro_rel3"];
            [param_dic setValue:@"" forKey:@"goods_pro_rel4"];
            [param_dic setValue:@"" forKey:@"goods_pro_rel5"];
            [param_dic setValue:itemDic[@"thNormalType"] forKey:@"thnormaltype"];
           
            NSArray *arr = [NSArray arrayWithObject:param_dic];
            NSDictionary *resultDic = [NSDictionary dictionaryWithObject:arr forKey:@"orderInfo"];
            NSLog(@"%@",param_dic);
            
            Mediator *mediator = [Mediator sharedInstance];
            UIViewController *orderVC = [mediator BKOrder_orderViewControllerWithParameter:resultDic];
            orderVC.view.backgroundColor = ThemeBackgroundColor;
            [self.navigationController pushViewController:orderVC animated:YES];
            
        }else{
            if ([obj[@"msg"]isKindOfClass:[NSString class]]) {
                kOrderPromptMsg(obj[@"msg"]);
            }
        }
    }];
}





-(void)Create_marr_Section{
    
    _marr_Section=[[NSMutableArray alloc]init];
    NSMutableArray *Cells = [NSMutableArray array];

    CellModel *cell0 = [[CellModel alloc] init];
    cell0.className = NSStringFromClass([BKExchangeGoodsCell class]);
    cell0.reuseIdentifier = NSStringFromClass([BKExchangeGoodsCell class]);
//    cell0.height = [BKExchangeGoodsCell getCellHeightFromInfo:self.model heightForRowAtIndexPath:indexPath];
    cell0.selectionStyle = UITableViewCellSelectionStyleNone;
    //            gc.userInfo = goods;
    [Cells addObject:cell0];
    
    
    CellModel *cell1 = [[CellModel alloc] init];
    cell1.className = NSStringFromClass([BKEXGoodsDetailCell class]);
    cell1.reuseIdentifier = NSStringFromClass([BKEXGoodsDetailCell class]);
//    cell1.height = [BKExchangeGoodsCell getCellHeightFromInfo:self.model heightForRowAtIndexPath:indexPath];
    cell1.selectionStyle = UITableViewCellSelectionStyleNone;
    //            gc.userInfo = goods;
    [Cells addObject:cell1];
    
    
    SectionModel *Section0 = [SectionModel sectionModelWithTitle:nil cells:Cells.copy];
    Section0.headerhHeight = 0.00001;
    Section0.footerHeight  = 0.00001;
    
    [_marr_Section addObject:Section0];
    
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
